import { NextRequest, NextResponse } from 'next/server'
import { addFavorite, removeFavorite, isFavorited, type StoredFavorite } from '@/lib/database'
import { randomUUID } from 'crypto'

// 检查收藏状态
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({
        success: false,
        error: '用户ID不能为空'
      }, { status: 400 })
    }

    const favorited = await isFavorited(userId, id)

    return NextResponse.json({
      success: true,
      data: { favorited }
    })
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    return NextResponse.json({
      success: false,
      error: '检查收藏状态失败'
    }, { status: 500 })
  }
}

// 添加收藏
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({
        success: false,
        error: '用户ID不能为空'
      }, { status: 400 })
    }

    // 检查是否已收藏
    const existingFavorite = await isFavorited(userId, id)
    if (existingFavorite) {
      return NextResponse.json({
        success: true,
        message: '已收藏'
      })
    }

    // 添加收藏
    const favorite: Omit<StoredFavorite, 'createdAt'> = {
      id: randomUUID(),
      toolId: id,
      userId
    }

    // 这里应该调用添加收藏的函数
    await addFavorite(favorite)

    return NextResponse.json({
      success: true,
      message: '收藏成功'
    })
  } catch (error) {
    console.error('添加收藏失败:', error)
    return NextResponse.json({
      success: false,
      error: '添加收藏失败'
    }, { status: 500 })
  }
}

// 取消收藏
export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json({
        success: false,
        error: '用户ID不能为空'
      }, { status: 400 })
    }

    // 移除收藏
    await removeFavorite(userId, id)

    return NextResponse.json({
      success: true,
      message: '取消收藏成功'
    })
  } catch (error) {
    console.error('取消收藏失败:', error)
    return NextResponse.json({
      success: false,
      error: '取消收藏失败'
    }, { status: 500 })
  }
}